<script lang="ts">
import { useAntdForm } from '@peng_kai/kit/antd';
import { InputOtp, InputPassword } from '~comp/input';
import Turnstile, { cfRules } from '~comp/Turnstile.vue';
import { useModalBindHash } from '~/composables/url';
import { flzxsqc } from '~/utils';
import { validatePassword } from '../helpers';

export const resetPasswordPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./ResetPassword.vue')),
  {
    title: toRef(() => $t('jkGMvmfX9akyN4gOox2')),
    wrapClassName: 'ant-cover__Modal-drawer __screen-drawer',
    width: 400,
    centered: true,
    footer: null,
    rejectOnClose: true,
    maskClosable: false,
    opener() {
      useModalBindHash({
        modalName: 'resetPassword',
        requireParamKeys: ['email'],
        requireAuth: false,
        isOpen: () => !!resetPasswordPopup.modalProps.open,
        open(hashParams) {
          resetPasswordPopup.open({
            email: hashParams.get('email')!,
            verifyCode: hashParams.get('verifyCode') || undefined,
          });
        },
        close: () => resetPasswordPopup.close(),
      });
    },
  },
);
</script>

<script setup lang="ts">
const props = defineProps<{ email: string; verifyCode?: string; onClose?: () => void }>();

const form = useAntdForm({
  email: {
    value: props.email,
    rules: [{ required: true, type: 'email', message: $t('aw95tLwTkGmrgSVCHW') }],
  },
  password: {
    value: '',
    rules: [{ validator: validatePassword }],
  },
  password_confirm: {
    value: '',
    rules: [{ validator(_, value) {
      if (!value)
        return formResult($t('tEk2LUqYvzBMTl7So2p8'));
      if (value !== form.state.password)
        return formResult($t('5Juinv2jAFlT6Jqo3Xwft'));
      return formResult();
    } }],
  },
  verify_code: {
    value: props.verifyCode ?? '',
  },
  cf_turnstile_response: {
    value: '',
    rules: cfRules,
  },
});

const turnstileDomRef = ref();

const resetPasswordMut = useMutation({
  mutationKey: [apis.apiAuthResetPassword.id],
  mutationFn: apis.apiAuthResetPassword.setDefaultConfig({
    successMessage: $t('zsaLk1KtXyRrJmdsq5Jo2'),
  }),
  onSuccess() {
    props.onClose?.();
  },
  onError() {
    turnstileDomRef.value?.reset?.();
    form.$form?.clearValidate?.();
  },
});

const getIsLoadingRef = computed(() => resetPasswordMut.isPending.value);

function confirm() {
  const requestBody = { ...form.state, password: flzxsqc(form.state.password), password_confirm: flzxsqc(form.state.password_confirm) };
  resetPasswordMut.mutate({ requestBody });
}
</script>

<template>
  <div>
    <AForm v-bind="form.props" class="ant-cover__Form-compact" hideRequiredMark :disabled="getIsLoadingRef" layout="vertical" @finish="confirm()">
      <AFormItem
        v-if="props.verifyCode"
        v-bind="form.itemProps.email"
        :label="$t('wxnfCdf43thnacVZgQa1')"
      >
        <AInput v-model:value="form.state.email" :placeholder="$t('hVaEobWzd70kjGP9Awnt')" disabled>
          <template #prefix>
            <i class="i-ri:mail-fill mr-1 text-1.2em text-sys-text-body" />
          </template>
        </AInput>
      </AFormItem>

      <AFormItem
        v-if="!props.verifyCode"
        v-bind="form.itemProps.verify_code"
        :label="$t('vrOaTrsSDoDwKhZqxWG')"
      >
        <InputOtp v-model:value="form.state.verify_code" />
        <template #extra>
          <div class="text-sys-text-body">
            {{ $t('dGidFaScfnTwMh8tC7R3e') }}: <span class="text-green">{{ props.email }}</span>.
          </div>
        </template>
      </AFormItem>

      <AFormItem v-bind="form.itemProps.password" :label="$t('ph7eJFfBmsn7xFyvj8')">
        <InputPassword v-model:value="form.state.password" :placeholder="$t('hwbK7ZZedFNtXjMoargn')" />
      </AFormItem>

      <AFormItem v-bind="form.itemProps.password_confirm" :label="$t('mrEblLvgr1ZXcaYe5EAbZ')">
        <InputPassword v-model:value="form.state.password_confirm" :placeholder="$t('efGc4obXamq6y0Onbwua')" />
      </AFormItem>

      <AFormItem v-bind="form.itemProps.cf_turnstile_response">
        <Turnstile ref="turnstileDomRef" v-model:value="form.state.cf_turnstile_response" />
      </AFormItem>

      <AButton
        class="ant-cover__Button-3d-primary mb-2 mt-4" htmlType="submit"
        type="primary" block :disabled="getIsLoadingRef" :loading="getIsLoadingRef"
      >
        {{ $t('fVhxPoy2u9I4Q6dqrMh') }}
      </AButton>
    </AForm>
  </div>
</template>
